import _ from 'underscore'
import $ from 'jquery'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
import TimeStore from 'lib/stores/time-store'
import widgetsApi from '../apis/widgets'
import {coreApi,combAnalysisApi,propConfig,parseToChart} from '../apis/core-util'
import ApiFactory from 'lib/ApiFactory'

function getOldViewKey(oldViewKey,url,params){
  if(oldViewKey==='val'&&url.indexOf('session.json')>-1){
    return 'session_count'
  }
  if(oldViewKey==='rate'){
    return 'error_rate'
  }
  if(oldViewKey==='avg_app_exec'){
    return 'avg_exec'
  }
  if(propConfig[oldViewKey]){
    return oldViewKey
  }
}
export default class MainScope extends Scope {
  constructor(){
    super();
    this.$state = {
      widgets:null
    }
    this.widgetGet = widgetsApi()
  }
  initWidgets(widgets){
    var _this = this
    this.$state.widgets = widgets.map(function(widget){
      var param = widget.requestParam?JSON.parse(widget.requestParam):{}
        , config = widget.config?JSON.parse(widget.config):{}
      if(param.isCombAnalysis){
        return _.extend({},widget,{
          requestParam:param,
          api:combAnalysisApi(param,TimeStore.getValue),
          config:config,
          store:{
            loading:true
          }
        })
      }else if(param.viewKey&&param.urlName){//新版
        return _.extend({},widget,{
          requestParam:param,
          api:coreApi(param,TimeStore.getValue),
          config:config,
          store:{
            loading:true
          }
        })
      }else if(config.viewKey){
        return _.extend({},widget,{
          requestParam:param,
          api:ApiFactory({
            url:widget.requestUrl,
            optionParams:['appId','urlName','viewKey','customClassify']
          })(_.extend({},param,config,{
            viewKey:getOldViewKey(config.viewKey,widget.requestUrl,param)
          }),TimeStore.getValue),
          config:config,
          store:{
            loading:true
          }
        })
      }else{
        return null
      }
    }).filter(function(w){
      return w
    })
    this.emit()
    this.$state.widgets.forEach(function(w){
      w.api.fetch().then(function(data,params){
        w.store = {
          data:w.config&&w.config.chartType==='pie'?parseToChart(_.extend({},data,{
            result:_(data.result).map(function(r){
              return _.extend({},r,{
                data:[r.combData]
              })
            })
          }),params):parseToChart(data,params)
        }
      },function(err){
        w.store = {error:err}
      }).always(function(){
        _this.emit()
      })
    })
  }
  fetch(){
    var _this = this
    this.widgetGet.fetch().then(this.initWidgets.bind(this))
  }
  $remove_widget(payload){
    $.ajax({
      url:BlueWare.urlPrefix+'/dashboard/'+BlueWare.dashboardId+'/widget/'+payload.id+'/delete',
      method:'post'
    }).done(function(result){
      if(result.result){
        Success('删除成功');
        this.$state.widgets = this.$state.widgets.filter(function(w){
          return w.id !== payload.id
        })
        this.emit()
      }else{
        Warning('删除失败')
      }
    }.bind(this)).fail(function(){
      Warning('删除失败')
    })
  }
  $settime(payload){
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
